package com.testlio.assignment.controller;

import com.testlio.assignment.dto.IssueDTO;
import com.testlio.assignment.dto.CreateIssueRequest;
import com.testlio.assignment.dto.UpdateIssueRequest;
import com.testlio.assignment.service.IssueService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * REST Controller for managing Issue resources.
 * Provides CRUD operations through REST endpoints.
 */
@RestController
@RequestMapping("/api/issues")
@AllArgsConstructor
public class IssueController {

    private IssueService issueService;

    /**
     * GET /api/issues : Get all issues.
     * @return List of all issues
     */
    @GetMapping
    public List<IssueDTO> getAllIssues() {
        return issueService.findAll();
    }

    /**
     * GET /api/issues/{id} : Get an issue by ID.
     * @param id The ID of the issue to retrieve
     * @return ResponseEntity containing the issue if found, or 404 if not found
     */
    @GetMapping("/{id}")
    public ResponseEntity<IssueDTO> getIssueById(@PathVariable Integer id) {
        return issueService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * POST /api/issues : Create a new issue.
     * @param request The create issue request
     * @return The created issue
     */
    @PostMapping
    public IssueDTO createIssue(@Valid @RequestBody CreateIssueRequest request) {
        return issueService.create(request);
    }

    /**
     * PUT /api/issues/{id} : Update an existing issue.
     * @param id The ID of the issue to update
     * @param request The update issue request
     * @return ResponseEntity containing the updated issue if found, or 404 if not found
     */
    @PutMapping("/{id}")
    public ResponseEntity<IssueDTO> updateIssue(
            @PathVariable Integer id,
            @Valid @RequestBody UpdateIssueRequest request) {
        return issueService.update(id, request)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    /**
     * DELETE /api/issues/{id} : Delete an issue.
     * @param id The ID of the issue to delete
     * @return ResponseEntity with no content if successful, or 404 if not found
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteIssue(@PathVariable Integer id) {
        return issueService.delete(id)
                ? ResponseEntity.ok().build()
                : ResponseEntity.notFound().build();
    }
}
